<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="出货时间" prop="shipmentDate">
        <el-date-picker
          v-model="queryParams.shipmentDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customer">
        <el-input
          v-model="queryParams.customer"
          placeholder="请输入客户"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="票号" prop="ticketNumber">
        <el-input
          v-model="queryParams.ticketNumber"
          placeholder="请输入票号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="厂内编号" prop="internalNumber">
        <el-input
          v-model="queryParams.internalNumber"
          placeholder="请输入厂内编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="型号(KP)" prop="modelKp">
        <el-input
          v-model="queryParams.modelKp"
          placeholder="请输入型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="FLEX" prop="flex">
        <el-input
          v-model="queryParams.flex"
          placeholder="请输入FLEX"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="方向" prop="direction">
        <el-input
          v-model="queryParams.direction"
          placeholder="请输入方向"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
                type="warning"
                plain
                @click="handleImport"
              >
                <Icon icon="ep:upload" /> 导入
              </el-button>
        <!--
        <el-button
            type="success"
            plain
            @click="handleOutport"
            :loading="exportLoading"
            v-hasPermi="['system:post:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 下载模板
          </el-button>
          -->
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['project:dispatch-list:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['project:dispatch-list:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" show-summary="true" :summary-method="getSummaries">
      <el-table-column type="index" label="序号" align="center" width="55" />
      <el-table-column label="出货时间" align="center" prop="shipmentDate">
        <template #default="scope">
          <span v-if="scope.row.shipmentDate">{{ formatDateArray(scope.row.shipmentDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customer" />
      <el-table-column label="票号" align="center" prop="ticketNumber" />
      <el-table-column label="厂内编号" align="center" prop="internalNumber" />
      <el-table-column label="型号（KP）" align="center" prop="modelKp" />
      <el-table-column label="FLEX" align="center" prop="flex" />
      <el-table-column label="打击板结构" align="center" prop="hammerPlateStructure" />
      <el-table-column label="打击板模号" align="center" prop="hammerPlateModel" />
      <el-table-column label="方向" align="center" prop="direction" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="长度" align="center" prop="productLength" />
      <el-table-column label="T/C/F" align="center" prop="tcf" />
      <el-table-column label="ST1271" align="center" prop="st1271" />
      <el-table-column label="是否待定" align="center" prop="bat" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DispatchListForm ref="formRef" @success="getList" />

  <!-- 导入对话框 -->
  <DispatchListImportForm ref="importFormRef" @success="getList" />
  <!-- 导出对话框 -->
  <DispathcListOutportForm ref="outportFormRef" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDateArray } from '@/utils/formatTime'
import download from '@/utils/download'
import { DispatchListApi, DispatchListVO } from '@/api/hcxly/dispatchList/Index'
import DispatchListForm from './DispatchListForm.vue'
import DispatchListImportForm from './DispatchListImportForm.vue'
import DispathcListOutportForm from './DispathcListOutportForm.vue'
import type { VNode } from 'vue'
import type { TableColumnCtx } from 'element-plus'

/** 派工单 列表 */
defineOptions({ name: 'DispatchList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DispatchListVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  shipmentDate: [],
  customer: undefined,
  ticketNumber: undefined,
  internalNumber: undefined,
  modelKp: undefined,
  flex: undefined,
  hammerPlateStructure: undefined,
  hammerPlateModel: undefined,
  direction: undefined,
  quantity: undefined,
  productLength: undefined,
  tcf: undefined,
  st1271: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DispatchListApi.getDispatchListPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DispatchListApi.deleteDispatchList(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DispatchListApi.exportDispatchList(queryParams)
    download.excel(data, '派工单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}


/** 导出 */
const outportFormRef = ref()
const handleOutport = () => {
  outportFormRef.value.open()
}


interface SummaryMethodProps<T = DispatchListVO> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
        '合计',
      ])
      return
    }
    if(column.property == 'quantity'){
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)}`
      }
    }
  })

  return sums
}


/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
